package com.example.pplication;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class AddTaskActivity extends AppCompatActivity {
    private EditText etTitle, etDescription;
    private Spinner spinnerPriority, spinnerCategory;
    private Button btnSave, btnSetDueDate, btnSetReminder;
    private Calendar dueDateCalendar = Calendar.getInstance();
    private Calendar reminderCalendar = Calendar.getInstance();
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
    private TaskManager taskManager;
    private long currentUserId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 深色模式适配
        SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
        boolean darkMode = prefs.getBoolean("dark_mode", false);
        AppCompatDelegate.setDefaultNightMode(
                darkMode ? AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO
        );

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_task);

        // 获取当前用户ID
        currentUserId = getCurrentUserId();
        taskManager = new TaskManager(this, currentUserId);

        // 初始化视图
        etTitle = findViewById(R.id.et_title);
        etDescription = findViewById(R.id.et_description);
        spinnerPriority = findViewById(R.id.spinner_priority);
        spinnerPriority.setAdapter(new ArrayAdapter<>(this,android.R.layout.simple_dropdown_item_1line,getResources().getStringArray(R.array.priority)));
        spinnerCategory = findViewById(R.id.spinner_category);
        spinnerCategory.setAdapter(new ArrayAdapter<>(this,android.R.layout.simple_dropdown_item_1line,getResources().getStringArray(R.array.category)));
        btnSave = findViewById(R.id.btn_save);
        btnSetDueDate = findViewById(R.id.btn_set_due_date);
        btnSetReminder = findViewById(R.id.btn_set_reminder);

        // 设置初始文本
        btnSetDueDate.setText(dateFormat.format(dueDateCalendar.getTime()));
        btnSetReminder.setText(timeFormat.format(reminderCalendar.getTime()));

        btnSetDueDate.setOnClickListener(v -> showDatePickerDialog());
        btnSetReminder.setOnClickListener(v -> showTimePickerDialog());
        btnSave.setOnClickListener(v -> saveTask());
    }

    private void showDatePickerDialog() {
        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                (view, year, month, dayOfMonth) -> {
                    dueDateCalendar.set(year, month, dayOfMonth);
                    btnSetDueDate.setText(dateFormat.format(dueDateCalendar.getTime()));
                },
                dueDateCalendar.get(Calendar.YEAR),
                dueDateCalendar.get(Calendar.MONTH),
                dueDateCalendar.get(Calendar.DAY_OF_MONTH)
        );
        datePickerDialog.show();
    }

    private void showTimePickerDialog() {
        TimePickerDialog timePickerDialog = new TimePickerDialog(
                this,
                (view, hourOfDay, minute) -> {
                    reminderCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                    reminderCalendar.set(Calendar.MINUTE, minute);
                    btnSetReminder.setText(timeFormat.format(reminderCalendar.getTime()));
                },
                reminderCalendar.get(Calendar.HOUR_OF_DAY),
                reminderCalendar.get(Calendar.MINUTE),
                true
        );
        timePickerDialog.show();
    }

    private void saveTask() {
        String title = etTitle.getText().toString().trim();
        String description = etDescription.getText().toString().trim();
        String priority = spinnerPriority.getSelectedItem().toString();
        String category = spinnerCategory.getSelectedItem().toString();
        String dueDate = btnSetDueDate.getText().toString();
        String reminderTime = btnSetReminder.getText().toString();

        if (title.isEmpty()) {
            Toast.makeText(this, "请输入任务标题", Toast.LENGTH_SHORT).show();
            return;
        }

        long taskId = taskManager.addTask(title, description, priority, category, dueDate, reminderTime);

        if (taskId != -1) {
            Toast.makeText(this, "任务已保存", Toast.LENGTH_SHORT).show();
            setResult(RESULT_OK);
            finish();
        } else {
            Toast.makeText(this, "保存任务失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    private long getCurrentUserId() {
        SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
        return prefs.getLong("current_user_id", -1);
    }
}